import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:geomancy/models/base_model.dart';
import 'package:geomancy/providers/user_provider.dart';
import 'package:geomancy/tools/constant.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

class LocalStorage {
  LocalStorage._internal();
  static final LocalStorage _instance = LocalStorage._internal();
  static SharedPreferences? _prefs;

  // 初始化方法
  static Future<void> init() async {
    _prefs ??= await SharedPreferences.getInstance();
  }

  factory LocalStorage() => _instance;

  static Future<LocalStorage> getInstance() async {
    if (_prefs == null) {
      await init();
    }
    return _instance;
  }

  Future<bool> setString(String key, String value) {
    return _prefs!.setString(key, value);
  }

  String? getString(String key) {
    return _prefs!.getString(key);
  }

  Future<bool> setBoolean(String key, bool value) {
    return _prefs!.setBool(key, value);
  }

  bool? getBoolean(String key) {
    return _prefs!.getBool(key);
  }

  Future<bool> remove(String key) {
    return _prefs!.remove(key);
  }

  Future<bool> setStringList(String key, List<String> value) {
    return _prefs!.setStringList(key, value);
  }

  List<String>? getStringLIst(String key) {
    return _prefs!.getStringList(key);
  }

  void clear() {
    _prefs!.remove(Constant.TOKEN);
    _prefs!.remove(Constant.USER);
  }

  static Future<void> getLocalData(BuildContext context) {
    // 使用同步方法获取 Provider，避免 BuildContext 跨异步间隙
    final userProvider = context.read<UserProvider>();
    
    return Future(() async {
      if (_prefs == null) {
        await init();
      }
      try {
        final String? token = _prefs!.getString(Constant.TOKEN);
        final String? userStr = _prefs!.getString(Constant.USER);
        
        if (token != null && token.isNotEmpty) {
          userProvider.saveToken(token);
        }
        
        if (userStr != null) {
          final tmp = jsonDecode(userStr);
          if (tmp != null) {
            final User user = User.fromJson(tmp);
            userProvider.saveUserInfo(user);
          }
        }
      } catch (e) {
        debugPrint('LocalStorage getLocalData error: $e');
      }
    });
  }
}